package controller;

import java.io.IOException;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import component.HttpClient;
import component.Sender;
import dto.Protocol;
import dto.ResponseDto;
import dto.StatusDto;
import pojo.Merchant;
import service.FileUploadService;
import service.MerchantService;
import util.JsonUtil;

@Controller
@Configuration
@PropertySource("classpath:default.properties")
public class MerchantController {
	
	private final static Logger logger = LogManager.getLogger(MerchantController.class);
	
	
    @Resource(name = "merchantServiceImpl")
    private MerchantService merchantService;
    @Resource(name="merchantSender")
    private Sender sender;
    @Resource
    Environment env;
    @Resource(name="fileUploadService")
    private FileUploadService uploadService;
    @Resource(name="jerseyClient")
	private HttpClient httpClient;

    @RequestMapping(value = "/user/register", method = RequestMethod.POST)
    public String register(Merchant merchant, MultipartFile idCard, MultipartFile avatar, Model model) {
		String avatarSavePath = env.getProperty("avatar.savePath");
		String idCardSavePath = env.getProperty("idCard.savePath");
		String url = env.getProperty("image.server.url");
        System.out.println(avatar.getOriginalFilename());
        String[] names = avatar.getOriginalFilename().split("\\.");
        String suffix = names[names.length-1];
        String avatarKey = avatarSavePath+UUID.randomUUID().toString()+"."+suffix;
        merchant.setAvatarPath(avatarKey); 
        ResponseDto avatarResponse;
		try {
			avatarResponse = uploadService.upload(url,avatar.getInputStream(), avatarKey);
			 if (avatarResponse.getCode()!=1) {
					model.addAttribute("error", "error happen");
					return "redirect:/register.jsp";
				}
		     String[] idNames = avatar.getOriginalFilename().split("\\.");
		     String idSuffix = names[idNames.length-1];
		     String idKey = idCardSavePath+UUID.randomUUID().toString()+"."+idSuffix;
		     merchant.setIdCardPath(idKey);
		        
		     ResponseDto idCardResponse= uploadService.upload(url,idCard.getInputStream(), idKey);
		     if (idCardResponse==null||idCardResponse.getCode()!=1) {
		    	 model.addAttribute("error", "error happen");
		    	 return "redirect:/register.jsp";
			}
		    Protocol sendProtocol = new Protocol(merchant.getName(), merchant.getAddress(), merchant.getIdCardPath(), merchant.getAvatarPath(), Protocol.REGISTER);
		    sender.send(JsonUtil.toJsonString(sendProtocol));
		    try {
		        merchantService.register(merchant);
			} catch (Exception e) {
				model.addAttribute("error", "账号名已被使用，请更换");
				return "redirect:/register.jsp";
			}
		   return "redirect:/login.jsp";
		} catch (IOException e1) {
			logger.error(e1);
			return "redirect:/register.jsp";
		}
    }
    
    @RequestMapping(value = "/user/reRegister", method = RequestMethod.POST)
    public String reRegister(Merchant merchant, MultipartFile idCard, MultipartFile avatar,Model model,HttpSession session) {
    	Merchant loginUser = (Merchant) session.getAttribute("user");
    	merchant.setId(loginUser.getId());
    	merchant.setName(loginUser.getName());
        String avatarSavePath = env.getProperty("avatar.savePath");
        String idCardSavePath = env.getProperty("idCard.savePath");
		String url = env.getProperty("image.server.url");
        System.out.println(avatar.getOriginalFilename());
        String[] names = avatar.getOriginalFilename().split("\\.");
        String suffix = names[names.length-1];
        String avatarKey = avatarSavePath+UUID.randomUUID().toString()+"."+suffix;
        merchant.setAvatarPath(avatarKey); 
        ResponseDto avatarResponse;
		try {
			avatarResponse = uploadService.upload(url,avatar.getInputStream(), avatarKey);
			 if (avatarResponse.getCode()!=1) {
					model.addAttribute("error", "error happen");
//					return "register";
				}
		     String[] idNames = avatar.getOriginalFilename().split("\\.");
		     String idSuffix = names[idNames.length-1];
		     String idKey = idCardSavePath+UUID.randomUUID().toString()+"."+idSuffix;
		     merchant.setIdCardPath(idKey);
		        
		     ResponseDto idCardResponse= uploadService.upload(url,idCard.getInputStream(), idKey);
		     if (idCardResponse==null||idCardResponse.getCode()!=1) {
		    	 model.addAttribute("error", "error happen");
//				return "register";
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
        Protocol sendProtocol = new Protocol(merchant.getName(), merchant.getAddress(), merchant.getIdCardPath(), merchant.getAvatarPath(), Protocol.MODIFY);
        sender.send(JsonUtil.toJsonString(sendProtocol));
        merchantService.reRegister(merchant);
        return "redirect:/login.jsp";
       
    }

    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public String login(Merchant merchant,Model model,HttpSession session) {
        String result = merchantService.login(merchant);
        	if(result.equals("name error")){
        		model.addAttribute("error", "name error");
        		return "redirect:/views/login/name error";
        	}
        	else if(result.equals("password error")){
        		model.addAttribute("error", "password error");
        		return "redirect:/views/login/password error";
        	}
        	
        	session.setAttribute("user", merchantService.findByName(merchant));
        	System.out.println(merchant.getFoodList().size());
        return "redirect:/views/foods";
    }
    
    @RequestMapping(value="views/login/{error}")
    public String login(@PathVariable("error")String error,Model model) {
    	System.out.println(error);
    	model.addAttribute("error", error);
    	return "login";
    }
    
    @RequestMapping(value="/user/logout")
    public String logout(HttpSession session) {
    	session.removeAttribute("user");
    	 return "redirect:/login.jsp";
    }
    
    @ResponseBody
    @RequestMapping(value = "/user/status", method = RequestMethod.GET)
    public StatusDto getStatue(HttpServletRequest request) {
		Merchant merchant = (Merchant) request.getSession().getAttribute("user");
		String name = merchant.getName();
        String status = null;
        StatusDto statusDto = new StatusDto();
        try {
        	status = httpClient.get(env.getProperty("get.status.url") + name);
//        	status = HttpUtil.getResponseStr(env.getProperty("get.status.url"));
        	 statusDto = (StatusDto) JsonUtil.toJsonObject(status, StatusDto.class);
		} catch (Exception e) {
//			e.printStackTrace();
			statusDto.setStatus("out");
			return statusDto;
		}
        return statusDto;
	}
    
    
    @RequestMapping(value="/views/register/info")
    public String registerInfo() {
    	return "/WEB-INF/merchant/reRegister";
    }
    
    
    @RequestMapping(value="error")
    public String dealError(String info,Model model){
    	if(info==null){
    		model.addAttribute("info", "error happen");
    	}
    	return "error";
    }
    
   
}
